package com.xianan.xuhui.netsecurityproject.utils;

import com.xianan.xuhui.netsecurityproject.domain.token.WebSessionDto;
import com.xianan.xuhui.netsecurityproject.exception.BizException;
import com.xianan.xuhui.netsecurityproject.exception.BizExceptionEnum;

/**
 * @author xiaoli
 * @description 服务端存储token(session)
 * @since 2025/3/25 10:15
 */
public class WebSessionUtil {
    private static final ThreadLocal<WebSessionDto> Web_SESSION_DTO_THREAD_LOCAL = new ThreadLocal<WebSessionDto>();

    /**
     * 获得用户基本信息VO
     *
     * @return
     */
    public static WebSessionDto get() {
        return null == Web_SESSION_DTO_THREAD_LOCAL.get() ? new WebSessionDto() : Web_SESSION_DTO_THREAD_LOCAL.get();
    }

    /**
     * 清除信息
     */
    public static void remove() {
        if (Web_SESSION_DTO_THREAD_LOCAL!=null&&Web_SESSION_DTO_THREAD_LOCAL.get()!=null){
            Web_SESSION_DTO_THREAD_LOCAL.remove();
        }
    }

    /**
     * 获得用户uid
     * @return
     */
    public static Long getId() {
        if (get().getId() == null){
            throw new BizException(BizExceptionEnum.SESSION_NOT_FIND_ERROR);
        }
        return get().getId();
    }
    /**
     * 获得用户名
     *
     * @return 用户id
     */
    public static String getEmail() {
        return get().getEmail();
    }

    /**
     * 获得用户token
     *
     * @return 用户token
     */
    public static String getToken() {
        return get().getToken();
    }

    /**
     * 获取用户终端类型
     * @return
     */
    public static Integer getClientType(){
        return get().getClientType();
    }

    /**
     * 获取OpenId
     * @return
     */
    public static String getOpenId(){
        return get().getOpenId();
    }

    /**
     * 获取Unionid
     * @return
     */
    public static String getUnionid(){
        return get().getUnionid();
    }
    /**
     * 添加用户基本信息
     *
     * @param webSessionDto
     */
    public static void set(WebSessionDto webSessionDto) {
        if (null == webSessionDto) {
            webSessionDto = new WebSessionDto();
        }
        Web_SESSION_DTO_THREAD_LOCAL.set(webSessionDto);
    }
}
